#!/usr/bin/env python
import sys
import os
import scriptutil as su
from optparse import OptionParser

def concat(file1,file2):
	#Loop through file1 writing each line to the new file
	f1 = open(file1)
	cwd = os.getcwd()
	f1path = file1.split("/")
	f3name = cwd+"/data/"+f1path[-2][:4]+"R.txt"
	f3 = open(f3name,'w')
	print "\nCopying File 1 into new file"
	for line in f1:
		f3.write(line)
	f1.close()
	#In order to retrieve the last FeatureNum, Row, and Col numbers from the first file, read the last line of file1.
	f1 = open(file1)	
	last = f1.readlines()[-1]
	l = last.split("\t")
	print "\nLast Line of File 1: "
	print l[:4]
	fnum = int(l[1])
	row = int(l[2])
	col = int(l[3])
	f1.close()

	#Loop through file2 line by line discarding lines until you find the second '*'.
	# discard the next two or so lines until you get to the line starting with 'DATA'
	# then start appending the lines onto file3
	count =0
	f2 = open(file2)
	
	print "\nAdding File 2 to a new file:"
	print "\tFeature\tRow\tCol"

	while count < 3: 
		line = f2.readline()
		if count < 2:
			if '*' in line:
				count = count+1
		else:
			if 'DATA' in line[:10]:
				l = line.split("\t")
				fnum = fnum + 1
				if col < 456:
					col = col +1
				else:
					col = 1
					row = row +1
			
				l[1] = str(fnum)
				l[2] = str(row)
				l[3] = str(col)
				print l[:4]
				line = "\t".join(l)
				f3.write(line)
				count = count+1
	count = 1
	for line in f2:
		if 'DATA' in line[:10]:
			l = line.split("\t")
			fnum = fnum + 1
			if col < 456:
				col = col +1
			else:
				col = 1
				row = row +1
		
			l[1] = str(fnum)
			l[2] = str(row)
			l[3] = str(col)
			if count<3:
				print l[:4]
			line = "\t".join(l)
			f3.write(line)
			count = count+1

	print " ......   .......   ....  .."
	f3.close()
	f3 = open(f3name)
	#Print last line of new file
	last = f3.readlines()[-1].strip()
	l = last.split("\t")
	print l[:4]
	print "File Concatenate Successful"
	print "New file located at: "+f3name
	f2.close()
	f3.close()
	return

if __name__=="__main__":
	parser = OptionParser()
	parser.add_option('-1', '--file1', dest='file1',
		help='File you want to append to', metavar='FILE')

	parser.add_option('-2', '--file2', dest='file2',
		help='File you want to append at the end of File 2', metavar='FILE')

	parser.add_option('-p', '--path', dest='path', default='.',
		help='Specify experiment number and I will search for the files', metavar='VAR')

	parser.add_option('-e', '--experiment', dest='experiment',
		help='Specify experiment number and I will search for the files', metavar='VAR')

	parser.add_option('-v', action='store_true', dest='verbose', default=False,
		help='Create verbose output (for testing)')

	(options, args) = parser.parse_args()
	#Search for files from a certain experiment name - Not yet functional
	if options.experiment != None:
		exp = str(options.experiment+'*')
		flist = su.ffind(options.path, exp)
		print "Files Found:"
		su.printr(flist)

	if options.file1 == None or not os.path.exists(options.file1):
		parser.error('Invalid input for File 1')
	if options.file2 == None or not os.path.exists(options.file2):
		parser.error('Invalid input for File 2')
	
	concat(options.file1,options.file2)
